 <!DOCTYPE html>

<html>
	<head>
	
	</head>
	<body>
 <?php 
	header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
	header('content-type: application/json; charset=utf-8');
	header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
	header("Access-Control-Allow-Origin: *");
	ini_set("allow_url_fopen", true);
	
	require 'include/mysql_connect.php';
	include_once "include/Functions.php";
	@set_time_limit(300);
	
	//print_r($_GET);
	//print_r($_POST);
	
	$data = file_get_contents("php://input");
	
	$data = utf8_encode($data);
	//var_dump(json_decode($data, true));
	//var_dump(json_decode($HTTP_RAW_POST_DATA, true));
	
	//[0] => dados do exercicio
	//[1] => path
	//[2] => estatisticas
	$obj = json_decode($data, true);

	$img_token = md5(uniqid(rand(), true));

	//$file= fopen("log.txt","a");
	$today= date("d/m/y - H:i:s");
	$tam_real= count($obj, COUNT_RECURSIVE);
	$log= "Data: {$today} ExerciceId: {$obj[0]['id']} detail_quant: {$obj[0]['tam']} statistics_quant: {$obj[0]['tam_estatistics']} tam_real_array: {$tam_real}\n";
	@file_put_contents("log.txt", $log, FILE_APPEND | LOCK_EX);

   //TODO: pegar o fuso do user
   $time_to_add = 3 * 60 * 60 * 1000;
   $obj[0]['ex_date_time']+= $time_to_add;
	//echo $img_token;
	//Exercise data
	$sql= "INSERT INTO exercise(id, name, ex_date_time, id_plan, id_type, id_person, 
		  duration, distance, speed, max_speed, calories, avg_hr, max_hr, pace, img_route, 
		  is_indoor, last_change, exported, score, plan_percent, cadence, description, mode_id,
		  elevation_gain, is_pace) 
		  VALUES ({$obj[0]['id']},
				  '{$obj[0]['name']}',
				  '{$obj[0]['ex_date_time']}',
				  '{$obj[0]['plan_id']}',
				  '{$obj[0]['type_id']}',
				  '{$obj[0]['person_id']}',
				  '{$obj[0]['duration']}',
				  '{$obj[0]['distance']}',
				  '{$obj[0]['speed']}',
				  '{$obj[0]['max_speed']}',
				  '{$obj[0]['calories']}',
				  '{$obj[0]['avg_hr']}',
				  '{$obj[0]['max_hr']}',
				  '{$obj[0]['pace']}',
				  '{$img_token}',
				  '{$obj[0]['is_indoor']}',
				  '{$obj[0]['last_change']}',
				  '{$obj[0]['exported']}',
				  '{$obj[0]['score']}',
				  '{$obj[0]['plan_percent']}',
				  '{$obj[0]['cadence']}',
				  '{$obj[0]['description']}',
				  '{$obj[0]['mode_id']}',
				  '{$obj[0]['elevation_gain']}',
				  '{$obj[0]['is_pace']}')";
	//echo $sql;
	mysql_query($sql) or die("Erro ao inserir dados exercicio!\n".mysql_error());
	
	//Data details
	$tam= $obj[0]["tam"];
	$sql = "INSERT INTO data_exerc(id_exerc, id_person, d_time, lat, lon, 
			  hrm, alt, speed, accuracy) 
			  VALUES ";

   //update fuso horario
   for($i=0; $i < $tam; $i++)
      $obj[1][$i]['d_time']+= $time_to_add;
           
	$rest = false;
   
   //grava apenas 600 registros
	if($tam > 600)
		$inc = (int) ceil($tam / 600);   
      
	for ($i=0; $i < $tam; $i+=$inc){
		$rest= true;
      $accuracy= $obj[1][$i]['accuracy'] * 10;
		$sql.= "('{$obj[0]['id']}',
			  '{$obj[0]['person_id']}',
			  '{$obj[1][$i]['d_time']}',
			  '{$obj[1][$i]['lat']}',
			  '{$obj[1][$i]['lon']}',
			  '{$obj[1][$i]['hrm']}',
			  '{$obj[1][$i]['alt']}',
			  '{$obj[1][$i]['speed']}',
			  '{$accuracy}'),";
	
		if( $i % 300 == 0){
			$rest = false;
			$sql = rtrim($sql,",");
			$sql.=';';
			mysql_query($sql) or die("Erro ao inserir dados detalhes!");
			$sql = "INSERT INTO data_exerc(id_exerc, id_person, d_time, lat, lon, 
					  hrm, alt, speed, accuracy) 
					  VALUES ";
		}
	}
					
   //TODO: adicionar o ultimo registro
	if( $rest){
		$sql = rtrim($sql,",");
		$sql.=';';
		mysql_query($sql) or die("Erro ao inserir dados detalhes!");	
	}

	//Data estatisticas
	$tam_est= $obj[0]["tam_estatistics"];
	for ($i=0; $i < $tam_est; $i++){
		$sql= "INSERT INTO estatistics(id_person, id_exerc, km, total_time, d_time, hrm, speed, max_speed, ascent, descent, elevation_gain, 
									   cadence, max_cadence) 
		VALUES ('{$obj[0]['person_id']}',
			  '{$obj[0]['id']}',
			  '{$obj[2][$i]['km']}',
			  '{$obj[2][$i]['total_time']}',
			  '{$obj[2][$i]['d_time']}',
			  '{$obj[2][$i]['hrm']}',
			  '{$obj[2][$i]['speed']}',
			  '{$obj[2][$i]['max_speed']}',
			  '{$obj[2][$i]['ascent']}',
			  '{$obj[2][$i]['descent']}',
			  '{$obj[2][$i]['elevation_gain']}',
			  '{$obj[2][$i]['cadence']}',
			  '{$obj[2][$i]['max_cadence']}')";
			  //echo $sql;
			  mysql_query($sql);//or die("Erro ao inserir dados!");
	}			   
   
	//Save image of path
	$path= "";
	$inc = 1;
	if($tam > 90)
		$inc = (int) ceil($tam / 90);

	$path = "http://maps.googleapis.com/maps/api/staticmap?size=250x150&path=color:0xff0000ff|weight:5";
	for( $i=0; $i < $tam; $i+= $inc ) {
		$latitude= round($obj[1][$i]['lat'], 6);
		$longitude= round($obj[1][$i]['lon'], 6);
		$path.= "|{$latitude},{$longitude}";
	}				
	
	echo "<script src='https://maps.googleapis.com/maps/api/js?key=AIzaSyDLsD5QOg-xebwva4wTUSCelvjSRAmGT1c&sensor=true'></script>";
	$img = 'images/maps/'.$img_token.'.png';
	@file_put_contents($img, @file_get_contents($path));			
	
	$msg= "success";
	/*$img= "images/maps/68085a692da361d197b146a7315daba0.png";
				$imgbinary = fread(fopen($img, "r"), filesize($img));
	$img_base64= base64_encode($imgbinary);			*/
		
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "http://www.alturarunning.bugs3.com/pages/process_achievement.php?exercise_id={$obj[0]['id']}&user_id={$obj[0]['person_id']}");
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
	//curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);	
	//if (curl_exec($ch) === FALSE) 
		//echo "Curl Failed: " . curl_error($ch);
	curl_exec($ch);		
	//curl_getinfo($ch);
	curl_close($ch);
	
	$sql = "SELECT strava_token, strava_token_type, strava_id, strava_export 
			FROM person
			WHERE id = {$obj[0]['person_id']}";
	
	$strava = Functions::getArraySql($sql);
	if( $strava['strava_export']){
		$date = date("Y-m-d\TH:i:s\Z", $obj[0]['ex_date_time']/1000 );
			
		$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<gpx creator=\"AlturaRunningGPX\" version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd\" xmlns:gpxtpx=\"http://www.garmin.com/xmlschemas/TrackPointExtension/v1\" xmlns:gpxx=\"http://www.garmin.com/xmlschemas/GpxExtensions/v3\">
 <metadata>
  <time>{$date}</time>
 </metadata>
 <trk>
  <name>{$obj[0]['name']} by alturarunning</name>
  <trkseg>\n";
			   
		for($i=0; $i < $obj[0]["tam"]; $i++){
			$date = date("Y-m-d\TH:i:s\Z", $obj[1][$i]["d_time"]/1000 );
			$lat = number_format($obj[1][$i]['lat'], 7);
			$lon = number_format($obj[1][$i]['lon'], 7);
			$alt = number_format($obj[1][$i]['alt'], 1);
			$xml.= "   <trkpt lat=\"{$lat}\" lon=\"{$lon}\">
    <ele>{$alt}</ele>
    <time>{$date}</time>\n";
	
	if( is_numeric($obj[1][$i]['hrm'])){
		$xml.="    <extensions>
	 <gpxtpx:TrackPointExtension>
	 <gpxtpx:hr>{$obj[1][$i]['hrm']}</gpxtpx:hr>
	 </gpxtpx:TrackPointExtension>
    </extensions>\n";
	}
	
			$xml.="   </trkpt>\n";
		}
		
		$xml.= "  </trkseg>
 </trk>
</gpx>\n";
			  
		//echo "<script> console.log({$xml}); </script>";
		$name_file = "tmp/{$img_token}.gpx";
		file_put_contents($name_file, $xml);
		
		//open connection
		$ch = curl_init();

		//set the url, number of POST vars, POST data
		curl_setopt($ch,CURLOPT_URL, "https://www.strava.com/api/v3/uploads");
		curl_setopt($ch,CURLOPT_POST, true);
		curl_setopt($ch,CURLOPT_POSTFIELDS,   array('file' => '@' . realpath($name_file), 'data_type'=> 'gpx'));
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $strava['strava_token_type'] .' '.$strava['strava_token']));
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		
		//execute post
		$result = curl_exec($ch);
		
		if ($result === FALSE) 
			echo "Curl Failed: " . curl_error($ch);
		
		echo $result;	
		//$strava= json_decode($result, true);

		//close connection
		curl_close($ch);

      //TODO: remove file
      //unlink($name_file);
	}
	
		$json[] = array
		(
			'msg' => $msg,
			'img' => $img_token.'.png'
		);
	//echo json_encode($json);
	echo 'localJsonpCallback('.json_encode($json).');';	
	
	//echo "<script  type='text/javascript'> var my_url = 'pages/process_details.php?exercise_id={$obj[0]['id']}'; </script>";		
	//flush();	
?>

<script  type="text/javascript">
	/*console.log(my_url);
	$.ajax({
		type: 'GET',
		url: my_url
	});*/
</script>

</body>

</html>
